﻿using System;
using System.Threading;
using System.Runtime.InteropServices;
using Codeflows.Logging;

namespace Codeflows
{
    static class DiagnosticsUtility
    {
        private static ILogProvider _logProvider = new DefaultLogProvider();

        public static bool IsFatal(Exception exception)
        {
            while(exception != null)
            {
                if ((exception is OutOfMemoryException && !(exception is InsufficientMemoryException)) ||
                    exception is ThreadAbortException ||
                    exception is SEHException)
                {
                    return true;
                }

                exception = exception.InnerException;
            }

            return false;
        }

        public static CodeflowException CreateException(string format, Exception innerException)
        {
            var exception = new CodeflowException(format, innerException);
            Error("An error occurred while attempting to execute codeflow.", exception);
            return exception;
        }

        public static CodeflowException CreateException(string format, params object[] arguments)
        {
            var exception = new CodeflowException(format, arguments);
            Error("An error occurred while attempting to execute codeflow.", exception);
            return exception;
        }

        public static void Error(string message, Exception exception)
        {
            _logProvider.Error(message, exception);
        }

        public static void Verbose(string message)
        {
            _logProvider.Verbose(message);
        }

        public static void Verbose(string format, params object[] arguments)
        {
            _logProvider.Verbose(format, arguments);
        }

        public static void Warning(string message)
        {
            _logProvider.Warning(message);
        }

        public static void Warning(string format, params object[] arguments)
        {
            _logProvider.Warning(format, arguments);
        }

        public static void Information(string message)
        {
            _logProvider.Information(message);
        }

        public static void Information(string format, params object[] arguments)
        {
            _logProvider.Information(format, arguments);
        }

        public static void SetLogProvider(ILogProvider logProvider)
        {
            _logProvider = logProvider;
        }
    }
}
